import { message } from 'antd';
import router from 'umi/router';
import moment from 'moment';
import {
  areaDataList,
  getAdjAccoData,
  getAdjDetailData,
  insertDataOs,
  insertDataNs,
  updataData,
  getBaseInfoListOs,
  getBaseInfoListNs,
  getReceiveBaseInfoList,
  getSendBaseInfoList,
  getCustOs,
  getCustNs,
  getCustReceive,
  getCustSend,
  getEmpOs,
  getEmpNs,
  getEmpReceive,
  getEmpSend,
  bigAssList,
  selectbigAssList,
  getList,
  delCollection,
  startFiling,
  getCusCount,
  fetchImportDeclList,
  fetchDictionaries,
  getAccoName,
  updateInfoProgress,
  getProgress,
  getListIndependence,
  getListOrders,
  getListBilling,
  submitRev,
  confirmCollection,
  refreshProgress,
  getUpdateTsk,
  queryParamByArea,
  getInsBaseInfoListNs,
  updataDataNs,
} from '@/services/annualbasic';

export default {
  state: {
    // zj
    billUpdtWay: '1',
    differHdlWay: '1',
    activeKeyDetail: '1',
    userType: null,
    areaList: [],
    accuList: [],
    submitOs: 0,
    adjFlag: 0,
    includeDeduSign: 2,
    pageDataDetail: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    diffHandle: [],
    sameHandle: [{ differHdlWay: '1' }],
    fileListOld: [],
    dynamicColumn: [],
    // xbt
    updatePercent: 0,
    EXPORT_MERGE_TYPE: [
      {
        itemCode: 1,
        itemName: '合并',
      },
    ],
    ADJ_FINIASH_TYPE: [],
    PAY_FEES_WAY: [],
    cusCount: 0,
    expandForm: false,
    formFieldsValue: {},
    clt: {},
    declarationData: {},
    updateYmOpts: [],
    accoNameList: [],
    tabList: [
      { itemCode: '1', itemName: '待采集' },
      { itemCode: '3', itemName: '已采集' },
      { itemCode: '4', itemName: '申报中' },
      { itemCode: '5', itemName: '已申报' },
    ],
    activeKey: '1',
    pageData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    importDeclData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    pageImportData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
  },

  effects: {
    // xbt运行和客服
    *fetchList({ payload }, { call, put }) {
      const res = yield call(getList, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      if (res.success) {
        yield put({
          type: 'getList',
          payload: {
            data: res.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(res.message || '服务端错误');
      }
    },
    // 自主
    *getListIndependence({ payload }, { call, put }) {
      const res = yield call(getListIndependence, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      if (res.success) {
        yield put({
          type: 'getList',
          payload: {
            data: res.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(res.message || '服务端错误');
      }
    },
    // 接单
    *getListOrders({ payload }, { call, put }) {
      const res = yield call(getListOrders, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      if (res.success) {
        yield put({
          type: 'getList',
          payload: {
            data: res.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(res.message || '服务端错误');
      }
    },
    // 发单
    *getListBilling({ payload }, { call, put }) {
      const res = yield call(getListBilling, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      if (res.success) {
        yield put({
          type: 'getList',
          payload: {
            data: res.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(res.message || '服务端错误');
      }
    },
    // 是否五险合一
    *queryParamByArea({ payload }, { call }) {
      const res = yield call(queryParamByArea, payload);
      return res;
    },
    // 刷新进度
    *refreshProgress({ payload }, { call, put }) {
      const res = yield call(refreshProgress, payload);
      if (res.success) {
        yield put({
          type: 'refreshState',
          payload: res.data,
        });
      } else {
        message.warning(res.message || '服务端错误');
      }
    },
    // 提交运行
    *submitrun({ payload }, { call }) {
      const res = yield call(submitRev, payload);
      if (res.success) {
        message.success('提交成功');
      } else {
        message.warning(res.message || '服务端错误');
      }
      return res;
    },
    // 确认采集
    *confirmCollection({ payload }, { call }) {
      const res = yield call(confirmCollection, payload);
      if (res.success) {
        message.success('确认成功');
      } else {
        message.warning(res.message || '服务端错误');
      }
      return res;
    },

    *fetchCusCount({ payload }, { call, put }) {
      const res = yield call(getCusCount, payload);
      if (res.success) {
        yield put({
          type: 'updateModelData',
          payload: {
            cusCount: res.data,
          },
        });
      } else {
        message.warning(res.message || '服务端错误');
      }
      return res;
    },
    *delCollection({ payload }, { call }) {
      const res = yield call(delCollection, payload);
      return res;
    },
    *startFiling({ payload }, { call }) {
      const res = yield call(startFiling, payload);
      return res;
    },
    *fetchImportDeclList({ payload, callback }, { call, put }) {
      const res = yield call(fetchImportDeclList, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      if (res.success) {
        yield put({
          type: 'getImportDeclList',
          payload: {
            data: res.data,
            currentPage,
            pageSize,
          },
        });
        callback(res.data);
      } else {
        message.warning(res.message || '服务端错误');
      }
    },
    *fetchDictionaries({ payload }, { call, put }) {
      const res = yield call(fetchDictionaries, payload);
      if (res.success) {
        yield put({
          type: 'getDictionaries',
          payload: res.data,
        });
      } else {
        message.warning(res.message || '服务端错误');
      }
    },
    // zj
    *areaList({ payload }, { call, put }) {
      const res = yield call(areaDataList, payload);
      if (res.success) {
        yield put({
          type: 'areaDataList',
          payload: res.data,
        });
      } else {
        message.warning(res.message || '服务端错误');
      }
    },
    *getAdjAccoInfor({ payload }, { call, put }) {
      const res = yield call(getAdjAccoData, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      if (res.success) {
        yield put({
          type: 'getListDetail',
          payload: {
            data: res.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(res.message || '服务端错误');
      }
    },
    *getAdjAccoDetail({ payload }, { call, put }) {
      const res = yield call(getAdjDetailData, payload);

      if (res.success) {
        yield put({
          type: 'updateModelDataPage',
          payload: res.data,
        });
        yield put({
          type: 'getBigAss',
          payload: { areaId: res.data.areaId },
        });
      } else {
        message.warning(res.message || '服务端错误');
      }
    },
    *fetchDetails({ payload }, { call, put }) {
      let res = null;
      // 运行和客服;
      if (Number(payload.userType) === 4 || Number(payload.userType) === 1) {
        res = yield call(getBaseInfoListOs, { yearAdjTskId: payload.yearAdjTskId });
      }
      // 自主
      if (String(payload.userType) === 'independence') {
        res = yield call(getBaseInfoListNs, { yearAdjTskId: payload.yearAdjTskId });
      }
      // 接单
      if (String(payload.userType) === 'receive') {
        res = yield call(getReceiveBaseInfoList, { yearAdjTskId: payload.yearAdjTskId });
      }
      // 发单
      if (String(payload.userType) === 'send') {
        res = yield call(getSendBaseInfoList, { yearAdjTskId: payload.yearAdjTskId });
      }
      if (res.success) {
        yield put({
          type: 'updateModelData',
          payload: {
            declarationData: res.data,
          },
        });
      } else {
        message.warning(res.message || '服务端错误');
      }
      return res;
    },
    // 修改详情
    *getBaseInfo({ payload }, { call, put }) {
      let res = null;
      // 运行和客服;
      if (Number(payload.userType) === 4 || Number(payload.userType) === 1) {
        res = yield call(getBaseInfoListOs, {
          yearAdjTskId: payload.yearAdjTskId,
          tabClickState: payload.tabClickState,
        });
      }
      // 自主
      if (String(payload.userType) === 'independence') {
        res = yield call(getInsBaseInfoListNs, {
          yearAdjTskId: payload.yearAdjTskId,
          tabClickState: payload.tabClickState,
        });
      }
      // 接单
      if (String(payload.userType) === 'receive') {
        res = yield call(getReceiveBaseInfoList, {
          yearAdjTskId: payload.yearAdjTskId,
          tabClickState: payload.tabClickState,
        });
      }
      // 发单
      if (String(payload.userType) === 'send') {
        res = yield call(getSendBaseInfoList, {
          yearAdjTskId: payload.yearAdjTskId,
          tabClickState: payload.tabClickState,
        });
      }

      if (res.success) {
        yield put({
          type: 'updateModelDataPage',
          payload: res.data,
        });
      } else {
        message.warning(res.message || '服务端错误');
      }
    },
    *saveDataOs({ payload }, { call, select }) {
      const yearAdjTskId = yield select(state => state.annualbasic.yearAdjTskId);
      const res = yearAdjTskId
        ? yield call(updataData, { ...payload, yearAdjTskId })
        : yield call(insertDataOs, payload);
      if (res.success) {
        router.push(`/more/annualbasicadjust/index`);
      } else {
        message.warning(res.message || '服务端错误');
      }
    },
    *saveDataNs({ payload }, { call, select }) {
      const yearAdjTskId = yield select(state => state.annualbasic.yearAdjTskId);
      const res = yearAdjTskId
        ? yield call(updataDataNs, { ...payload, yearAdjTskId })
        : yield call(insertDataNs, payload);
      if (res.success) {
        router.goBack();
      } else {
        message.warning(res.message || '服务端错误');
      }
    },

    *getCust({ payload }, { call, put }) {
      let res = null;
      // 运行和客服;
      if (Number(payload.userType) === 4 || Number(payload.userType) === 1) {
        res = yield call(getCustOs, payload.oper);
      }
      // 自主
      if (String(payload.userType) === 'independence') {
        res = yield call(getCustNs, payload.oper);
      }
      // 接单
      if (String(payload.userType) === 'receive') {
        res = yield call(getCustReceive, payload.oper);
      }
      // 发单
      if (String(payload.userType) === 'send') {
        res = yield call(getCustSend, payload.oper);
      }

      const {
        pageArg: { currentPage, pageSize },
      } = payload.oper;
      if (res.success) {
        yield put({
          type: 'getListDetail',
          payload: {
            data: res.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(res.message || '服务端错误');
      }
    },
    *getEmp({ payload }, { call, put }) {
      let res = null;
      // 运行和客服;
      if (Number(payload.userType) === 4 || Number(payload.userType) === 1) {
        res = yield call(getEmpOs, payload.oper);
      }
      // 自主
      if (String(payload.userType) === 'independence') {
        res = yield call(getEmpNs, payload.oper);
      }
      // 接单
      if (String(payload.userType) === 'receive') {
        res = yield call(getEmpReceive, payload.oper);
      }
      // 发单
      if (String(payload.userType) === 'send') {
        res = yield call(getEmpSend, payload.oper);
      }
      const {
        pageArg: { currentPage, pageSize },
      } = payload.oper;
      if (res.success) {
        yield put({
          type: 'getListDetail',
          payload: {
            data: res.data,
            currentPage,
            pageSize,
          },
        });
        return res.success;
      }
      return message.warning(res.message || '服务端错误');
    },
    // 地区最大险种
    *getBigAss({ payload }, { call, put }) {
      const response = yield call(bigAssList, payload);
      if (response.success) {
        yield put({
          type: 'bigAssList',
          payload: response.data,
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    *getSelectBigAss({ payload }, { call, put }) {
      const response = yield call(selectbigAssList, payload);
      if (response.success) {
        if (response.data.length === 0) {
          const resArea = yield call(bigAssList, { areaId: payload.areaId });
          if (resArea.success) {
            yield put({
              type: 'bigAssList',
              payload: resArea.data,
            });
          }
        } else {
          yield put({
            type: 'bigAssList',
            payload: response.data,
          });
        }
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    // 详情页查看
    *fetchAccoName({ payload }, { call, put }) {
      const response = yield call(getAccoName, payload);
      if (response.success) {
        yield put({
          type: 'getAccoName',
          payload: response.data,
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    // 更新进度
    *updateInfoProgress({ payload }, { call }) {
      const res = yield call(updateInfoProgress, payload);
      return res;
    },
    // 获取进度
    *getProgress({ payload }, { call, put }) {
      const res = yield call(getProgress, payload);
      if (res.success) {
        yield put({
          type: 'updateProgress',
          payload: res.data,
        });
      } else {
        message.warning(res.message || '服务端错误');
      }
      return res.data.successProp;
    },
    // 调基修改
    *fetchUpdateTsk({ payload }, { call, select }) {
      const yearAdjTskId = yield select(state => state.annualbasic.yearAdjTskId);
      const areaId = yield select(state => state.annualbasic.areaId);
      const res = yield call(getUpdateTsk, { ...payload, areaId, yearAdjTskId });
      return res;
    },
  },

  reducers: {
    // xbt
    getList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = data.pageRecords && Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        pageData: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },
    // 更新进度
    refreshState(state, { payload }) {
      const { yearAdjTskId } = payload;
      const yearAdjTskState = payload.state;
      const tempPageData = JSON.parse(JSON.stringify(state.pageData));
      const newList = tempPageData.list.map(item => {
        const newItem = item;
        if (item.yearAdjTskId === yearAdjTskId) {
          newItem.state = yearAdjTskState;
        }
        return item;
      });
      return {
        ...state,
        pageData: {
          ...tempPageData,
          list: newList,
        },
      };
    },
    getImportDeclList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = data.pageRecords && Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        pageImportData: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    getDictionaries(state, { payload }) {
      let ADJ_FINIASH_TYPE1 = [];
      if (Array.isArray(payload.ADJ_FINIASH_TYPE)) {
        payload.ADJ_FINIASH_TYPE.unshift({ itemCode: 0, itemName: '全部' });
        ADJ_FINIASH_TYPE1 = payload.ADJ_FINIASH_TYPE;
      } else {
        ADJ_FINIASH_TYPE1 = [];
      }
      let PAY_FEES_WAY1 = [];
      if (Array.isArray(payload.PAY_FEES_WAY)) {
        payload.PAY_FEES_WAY.unshift({ itemCode: 0, itemName: '全部' });
        PAY_FEES_WAY1 = payload.PAY_FEES_WAY;
      } else {
        PAY_FEES_WAY1 = [];
      }
      return {
        ...state,
        ADJ_FINIASH_TYPE: ADJ_FINIASH_TYPE1,
        EXPORT_MERGE_TYPE: Array.isArray(payload.EXPORT_MERGE_TYPE)
          ? payload.EXPORT_MERGE_TYPE
          : [],
        PAY_FEES_WAY: PAY_FEES_WAY1,
      };
    },

    // 第一个值开始年月，第二个值结束年月，‘2011-01’形式
    handleUpdateYmOpts(state, { payload = [] }) {
      const result = [];
      const startTime = new Date(payload[0]);
      const endTime = new Date(payload[1]);
      // 日期处理
      while (endTime - startTime >= 0) {
        const year = startTime.getFullYear();
        const month =
          (startTime.getMonth() + 1).toString().length === 1
            ? `0${(startTime.getMonth() + 1).toString()}`
            : startTime.getMonth() + 1;
        result.push(`${year}-${month}`);
        startTime.setMonth(startTime.getMonth() + 1);
      }
      // 转化为下拉选项
      const updateYmOpts = result
        .filter(item => item !== payload[0]) // 过滤掉采集人员年月
        .map(item => ({
          label: item,
          value: moment(item).valueOf(),
        }));

      /* const result = [];
      const s = payload[0].split('-');
      const e = payload[1].split('-');
      const min = new Date();
      const max = new Date();
      min.setFullYear(s[0], s[1]);
      max.setFullYear(e[0], e[1]);
      const curr = min;
      while (curr <= max) {
        let month = curr.getMonth();
        if (month === 0) {
          month = 12;
          const tempObj = {};
          tempObj.label = `${curr.getFullYear()}-${month < 10 ? `0${month}` : month}`;
          tempObj.value = +curr;
          result.push(tempObj);
          curr.setMonth(1);
        } else {
          const tempObj = {};
          tempObj.label = `${curr.getFullYear()}-${month < 10 ? `0${month}` : month}`;
          tempObj.value = +curr;
          result.push(tempObj);
          curr.setMonth(month + 1);
        }
      } */
      return {
        ...state,
        updateYmOpts,
      };
    },
    // 更新进度
    updateProgress(state, { payload }) {
      return {
        ...state,
        updatePercent: payload.successProp,
      };
    },
    // zj
    updateModelDataPage(state, { payload }) {
      const newObj = payload;
      const newState = state;
      Object.keys(payload).forEach(key => {
        if (
          key === 'adjYm' ||
          key === 'adjTskBeginDate' ||
          key === 'adjTskEndDate' ||
          key === 'validYm'
        ) {
          newObj[key] = moment(payload[key]).format('YYYY-MM-DD');
        }
        if (String(payload.billUpdtWay) === '1') {
          newState.sameHandle = newObj.listAdjUpdt;
          newState.diffHandle = newObj.listAdjAssBrief.map(item => ({
            ...item,
            differHdlWay: 1,
          }));
        } else {
          newState.diffHandle = newObj.listAdjUpdt;
        }
        if (key === 'affix') {
          newState.fileListOld = [
            {
              uid: newObj[key].split('|')[0],
              name: newObj[key].split('|')[1],
            },
          ];
        }
      });
      return {
        ...state,
        ...payload,
      };
    },
    updateDetailtable(state, { payload }) {
      state.dynamicColumn.push(payload);
      return {
        ...state,
      };
    },
    // 获取列表
    getListDetail(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const newColumn = [
        {
          title: '姓名',
          dataIndex: 'empName',
        },
        {
          title: '证件号',
          dataIndex: 'certNo',
        },
        {
          title: '客户名称',
          dataIndex: 'custName',
        },
        {
          title: '签约方',
          dataIndex: 'ordSndrName',
        },
        {
          title: '采集险种',
          dataIndex: 'adjAssName',
          // render: text => text && text.map((item,index)=>{
          // return <span>{item.assName}{index+1 < text.length ? <span>、</span> : ''}</span>
          // })
        },
        {
          title: '所属负责人',
          dataIndex: 'blngCs',
        },
        {
          title: '备注',
          dataIndex: 'remark',
        },
      ];
      let list = [];
      const newData = data;
      if (data.assBriefVoList) {
        const oldData = data.assBriefVoList;
        list = Array.isArray(data.empAssList.pageRecords) ? data.empAssList.pageRecords : [];
        newData.totalCount = data.empAssList.totalCount;
        oldData.map(item => {
          const newObj = {};
          newObj.title = `${item.assName}工资（新）`;
          newObj.dataIndex = `aftPayWage_${item.ass}`;
          newObj.render = text => text || '--';
          newObj.onCell = () => ({
            style: {
              textAlign: 'left',
            },
          });
          newObj.onHeaderCell = () => ({
            style: {
              textAlign: 'left',
            },
          });
          return newColumn.splice(-2, 0, newObj);
        });
        const nes = list;
        list.map((c, j) => {
          const item = c.listAss;
          item.map(f => {
            nes[j][`aftPayWage_${f.ass}`] = f.aftPayWage || '--';
            return true;
          });
          return true;
        });
      } else {
        list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      }
      return {
        ...state,
        pageDataDetail: {
          list,
          pagination: { total: newData.totalCount, current: currentPage, pageSize },
        },
        dynamicColumn: newColumn,
      };
    },

    // 新增上传文件
    updateData(state, { payload }) {
      return {
        ...state,
        fileListOld: payload && payload.length && [payload[0]],
      };
    },
    updateDel(state) {
      return {
        ...state,
        fileListOld: state.fileListOld && state.fileListOld.splice(state.fileListOld.length - 1, 1),
      };
    },
    getAdjAccoData(state, { payload }) {
      return {
        ...state,
        accuList: payload,
      };
    },
    areaDataList(state, { payload }) {
      return {
        ...state,
        areaList: payload,
      };
    },

    bigAssList(state, { payload }) {
      const diffHandle = [];
      // 修改
      if (state.yearAdjTskId) {
        for (let i = 0; i < state.listAdjUpdt && state.listAdjUpdt.length; i += 1) {
          for (let j = 0; j < payload.length; j += 1) {
            if (state.listAdjUpdt[i].ass === payload[j].ass) {
              diffHandle.push(Object.assign(state.listAdjUpdt[i], payload[j]));
            }
          }
        }
      }
      payload.forEach(item => {
        const newItem = item;
        newItem.differHdlWay = '1';
      });

      return {
        ...state,
        diffHandle: payload,
      };
    },
    getAccoName(state, { payload }) {
      return {
        ...state,
        accoNameList: payload,
      };
    },
  },
};
